<template>
  <n-drawer width="1500px" :close-on-esc="false" :mask-closable="false">
    <n-drawer-content title="大语言模型推理">
        <n-grid :x-gap="20">
          <n-grid-item :span="24" style="margin-bottom: 10px;">
            <n-alert type="warning" :show-icon="false">{{props.commonPromptSetting.warningText}}</n-alert>
          </n-grid-item>
          <n-grid-item :span="6">
            <n-form ref="promptFormRef">
              <n-form-item label="推理方案名称">
                <n-select  :options="promptOptions"  v-model:value="promptId" label-field="promptTitle" value-field="promptContent" :on-update:value="updatePromptTemplate"></n-select>
              </n-form-item>

              <n-form-item label="提示词模板">
                <n-input v-model:value="promptTemplate"
                         style="height: 400px" type="textarea"
                         ></n-input>
              </n-form-item>
            </n-form>
          </n-grid-item>
          <n-grid-item :span="18">

            <n-form v-if="commonPromptSetting.bizData.length == 1">
              <n-form-item label="文本内容">
                <n-input style="height: 250px" type="textarea" v-model:value="commonPromptSetting.bizData[0].content"></n-input>
              </n-form-item>
              <n-row>
                <n-col :span="12">
                  <n-button block type="info" @click="copyPrompt(0)">复制提示词</n-button>
                </n-col>
                <n-col :span="12" style="padding-left: 5px;">
                  <n-button block type="primary" @click="reason(0)">推理</n-button>
                </n-col>
              </n-row>

              <n-form-item label="推理结果" style="margin-top: 20px;">
                <n-input style="height: 250px" type="textarea" v-model:value="commonPromptSetting.bizData[0].result"></n-input>
              </n-form-item>

            </n-form>

            <n-scrollbar v-else>
              <n-space justify="space-between" style="margin-bottom: 5px;">
                <n-text>asdasd</n-text>
                <n-button size="small" type="primary"   >批量推理</n-button>
              </n-space>

              <n-data-table
                  :max-height="200"
                :data="props.commonPromptSetting?.bizData" :columns="createColumns">

              </n-data-table>
            </n-scrollbar>
          </n-grid-item>
        </n-grid>
        <template #footer>
          <n-button type="warning" style="margin-right: 20px;" @click="props.closeAction">
            关闭
          </n-button>
          <n-button ref="batchReason" type="primary" @click="props.commonPromptSetting?.saveResultFunction(props.commonPromptSetting?.bizData)">
            保存结果
          </n-button>
        </template>
    </n-drawer-content>
  </n-drawer>
</template>
<script setup lang="ts">
import {h, onMounted, ref, watch} from "vue"
//@ts-ignore
import {storeToRefs} from "pinia"
import {useSystemStore} from "@/store/modules/useSystemStore"
import {promptControllerApi} from "@/api/prompt/prompt.api";
import {SelectBaseOption} from "naive-ui/lib/select/src/interface";
import useClipboard from "vue-clipboard3";
import {NButton} from "naive-ui";
// 使用插件
const { toClipboard } = useClipboard();
let controller = new AbortController()


const promptOptions = ref(null)
const promptTemplate = ref(null)
const batchReason = ref(null)
const promptId = ref(null)

const {
  clientHeight,
  layoutHeaderHeight,
  darkTheme,
  tabsHeight
} = storeToRefs(useSystemStore());



const getPromptInfo = ()=>{
  promptControllerApi.getGptPromptOption(props.commonPromptSetting?.bizType).then((res)=>{
    if (res.code === 200){
      promptOptions.value = res.data
      if (res.data.length > 0){
        promptTemplate.value = res.data[0].promptContent
        promptId.value = res.data[0].promptTitle
      }
    }
  })
}

// 任务状态
const taskStatus = ref({
  successNum: 0,
  failNum: 0,
  totalNum: 0
})


const props = defineProps({
  commonPromptSetting:{
    type: Object as () => Chat.CommonPromptSetting,
    required: true
  },
  closeAction:{
    type: Function,
    required: true
  }
})


watch(() => props.commonPromptSetting.bizData, (val) => {
  getPromptInfo()
})

const updatePromptTemplate = (value:string,option: SelectBaseOption )=>{
  promptTemplate.value = value
  promptId.value = option.value.promptTitle
}


// 列表字段
const createColumns = [
  {
    type: 'selection'
  },
  {
    title: '文本内容',
    key: 'content',
    ellipsis: {
      tooltip: true,
      lineClamp: 3
    },
    width: 400,
  },
  {
    title: '推理结果',
    key: 'result',
    width: 300,
    ellipsis: {
      tooltip: true,
      lineClamp: 3
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 120,
    render(row:any) {
      return [h(
          NButton,
          {
            strong: true,
            tertiary: true,
            block: true,
            size: 'small',
            type: 'primary',
            onClick: () => reason(row.index)
          },
          { default: () => '文案推理' }
      ), h(
          NButton,
          {
            strong: true,
            tertiary: true,
            block: true,
            type: 'info',
            size: 'small',
            style: 'margin-top: 10px',
            onClick: () => copyPrompt(row.index)
          },
          { default: () => '提示词复制' }
      )]
    }
  }
]



onMounted(() => {
  getPromptInfo()
})



const copyPrompt = async (index:number) => {
  if (promptTemplate.value === null || promptTemplate.value === ''){
    window.$message.warning("请选择提示词模板...")
    return
  }
  try {
    const text = promptTemplate.value.replace('{{content}}', props.commonPromptSetting?.bizData[index].content);
    console.log(text)
    // 复制
    await toClipboard(text ,batchReason.value.$el);
    window.$message.success("复制成功...")
    // 复制成功
  } catch (e) {
    console.log(e)
    window.$message.error("复制失败，请手动复制...")
  }
}

const reason = async (index:number) => {
  if (promptTemplate.value === null || promptTemplate.value === ''){
    window.$message.warning("请选择提示词模板...")
    return
  }
  const data = {
    prompt: promptTemplate.value.replace('{{content}}', props.commonPromptSetting?.bizData[index].content),
    signal: controller.signal
  }
  const onDownloadProgress =  (event:any) => {
    const xhr = event.event.target
    const {responseText} = xhr
    props.commonPromptSetting.bizData[index].result = responseText
  }
  await promptControllerApi.commonReason(data,onDownloadProgress)
}

</script>
